from django.core.paginator import Paginator
from django.shortcuts import render
from django.views.generic import View
from django.shortcuts import HttpResponse
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.response import Response
import json

from new_list.models import Category, Blogs
from new_list.serializers import CatIndexSerializer
from new_list.new_go_v2 import refresh_new


class title(View):
    def get(self, request):
        category = Category.objects.all()
        data = {
            'categories': category,
            'old': int(request.COOKIES.get('cid')) if request.COOKIES.get('cid') else 1
        }

        response = HttpResponse(render(request, 'new_list.html', context=data))
        # 如果加载导航页就说明是从浏览器进入，可以获取到cid的话就将导航栏cookie设置为1，响应list时候将old设置为0，以此判断是否是从浏览器加载，以做到导航栏状态保存
        if request.COOKIES.get('cid'):
            response.set_cookie('old', '1')

        return response


class news_news_list(View):

    def get(self, resquest):
        cid = resquest.GET.get('cid', '1')
        page = resquest.GET.get('page')
        per_page = resquest.GET.get('per_page')

        if resquest.COOKIES.get('old') == '1':
            cid = resquest.COOKIES.get('cid')

        cid = int(cid)
        try:
            page = int(page)
            per_page = int(per_page)
        except:
            pass

        # 打开数据库
        if cid != 8:
            paginate = Blogs.objects.filter(category_id=cid).order_by('-create_time')
        else:
            paginate = Blogs.objects.all().order_by('-clicks')
        paginator = Paginator(paginate, 10)
        contacts = paginator.page(page)

        items = contacts
        # 获取到总页数
        if contacts.has_next():
            total_page = contacts.next_page_number()
        else:
            total_page = cid

        news_li = []
        # 获取每一个数据的详细数据
        for new in items:
            news_li.append(new.to_dict())

        data = {
            'total_page': total_page,
            'news_dict_li': news_li
        }
        response = HttpResponse(json.dumps(data), content_type="application/json")
        response.set_cookie('cid', cid)
        response.set_cookie('old', '0')
        return response


class news_get(View):
    """获取单一新闻对象"""

    def get(self, resquest, id):
        id = int(id)
        try:
            data = Blogs.objects.get(id=id)
        except:
            return HttpResponse('error')
        data.clicks += 1
        data.save()
        data = {
            'news': data.to_show()
        }
        return render(resquest, 'new_show.html', context=data)


class new_next(View):
    """获取下一个新闻"""

    def get(self, request):
        id = request.GET.get('id')
        move = request.GET.get('move')
        new_data = Blogs.objects.get(id=id)
        category = new_data.category_id
        time = new_data.create_time
        if move == 'up':
            data = Blogs.objects.filter(category_id=category).order_by('create_time').filter(
                create_time__gt=time).first()
        else:

            data = Blogs.objects.filter(category_id=category).order_by('-create_time').filter(
                create_time__lt=time).first()
        if not data:
            data = new_data

        data.clicks += 1
        data.save()

        data = {

            "news": data.to_show()

        }

        return HttpResponse(json.dumps(data), content_type="application/json")


class refresh(View):
    # 定义refresh机制用于马上刷新信息
    def post(self, request):
        refresh_id = request.POST.get('cid')
        if not isinstance(refresh, int):
            refresh_id = 0
        refresh_new(refresh_id)


class CatSearchViewSet(HaystackViewSet):
    """
    新闻搜索
    """
    index_models = [Blogs]

    serializer_class = CatIndexSerializer

    def get_queryset(self, index_models=[]):
        queryset = super(CatSearchViewSet, self).get_queryset()

        return queryset
